<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
	<th:block th:include="include :: header('外派结算-新增')" />
    <th:block th:include="include :: datetimepicker-css" />
    <th:block th:include="include :: select2-css" />
    <th:block th:include="include :: bootstrap-select-css" />
</head>
<body class="gray-bg">
    <div class="main-content">
        <form id="form-add" class="form-horizontal">
            <h4 class="form-header h4">结算信息</h4>
            <div class="row">
            	<div class="col-sm-6">
                    <div class="form-group">
                        <label class="col-sm-4 control-label is-required">客户：</label>
                        <div class="col-sm-8">
                            <select name="customerId" id="customerId"  class="form-control m-b" th:with="type=${@customDictService.selectDictCustomer()}" required>
                                <option value="">无</option>
                                <option th:each="dict : ${type}" th:text="${dict.title}" th:value="${dict.id}"></option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="col-sm-6">
                    <div class="form-group">
                        <label class="col-sm-4 control-label is-required">结算标题：</label>
                        <div class="col-sm-8">
                            <input id="title" name="title" placeholder="请输入" class="form-control" type="text" required>
                        </div>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-sm-6">
                    <div class="form-group">
                        <label class="col-sm-4 control-label is-required">结算金额：</label>
                        <div class="col-sm-8">
                            <input id="totalAmount" name="totalAmount" class="form-control" type="text" readonly>
                            <input name="settleStatus" type="hidden" value="N" />
                        </div>
                    </div>
                </div>
                <div class="col-sm-6">
                    <div class="form-group">
                        <label  class="col-sm-4 control-label">备注：</label>
                        <div class="col-sm-8">
                            <input type="text" name="description" class="form-control" id="description"/>
                        </div>
                    </div>
                </div>
            </div>

            <h4 class="form-header h4">结算账单</h4>
            <div class="row">
                <div class="col-sm-12">
                    <button type="button" class="btn btn-white btn-sm" onclick="addColumn()"><i class="fa fa-plus"> 增加</i></button>
                    <button type="button" class="btn btn-white btn-sm" onclick="removeBill()"><i class="fa fa-minus"> 删除</i></button>
                    <div class="col-sm-12 select-table table-striped">
					    <table id="bootstrap-table"></table>
					</div>
                </div>
            </div>
            <h4 class="form-header h4">PO列表</h4>
            <div class="row">
                <div class="col-sm-12">
                    <div class="col-sm-12 select-table table-striped">
                        <table id="bootstrap-table-po"></table>
                    </div>
                </div>
            </div>
            <h4 class="form-header h4"></h4>
            <div class="row">
                <div class="col-sm-offset-5 col-sm-10">
                    <button type="button" class="btn btn-sm btn-primary" onclick="submitHandler()"><i class="fa fa-check"></i>保 存</button>&nbsp;
                    <button type="button" class="btn btn-sm btn-danger" onclick="$.modal.closeTab()"><i class="fa fa-reply-all"></i>关 闭 </button>
                </div>
            </div>
        </form>
    </div>
      

    <th:block th:include="include :: footer" />
    <th:block th:include="include :: datetimepicker-js" />
    <th:block th:include="include :: select2-js" />
    <th:block th:include="include :: bootstrap-select-js" />
    <script th:src="@{/js/jquery.tmpl.js}"></script>
	<script th:inline="javascript">
        $("#form-add").validate({
            focusCleanup: true,
            rules:{
                totalAmount: {gt: 0}
            }
        });
        var isFinishDatas = [[${@dict.getType('sys_yes_no')}]];
	    $(function() {
	    	// 初始化数据, 可以由后台传过来
		    var options = {
                pagination: false,
		        showSearch: false,
                showRefresh: false,
                showToggle: false,
                showColumns: false,
                sidePagination: "client",
                columns: [
                    {
                        checkbox: true
                    },
                    {
                        field: 'id',
                        title: '',
                        visible: false
                    },
                    {
                        field: 'customerId',
                        title: '',
                        visible: false
                    },
                    {
                        field: 'projectName',
                        title: '项目名称'
                    },
                    {
                        field: 'personName',
                        width: '60px',
                        title: '姓名'
                    },
                    {
                        field: 'billYear',
                        title: '年'
                    },
                    {
                        field: 'billMonth',
                        title: '月'
                    },
                    {
                        field: 'workFee',
                        title: '工时费用',
                        footerFormatter:function (value) {
                            var sumBalance = 0;
                            for (var i in value) {
                                sumBalance += parseFloat(value[i].workFee);
                            }
                            return sumBalance.toFixed(2);
                        }
                    },
                    {
                        field: 'overtimeFee',
                        title: '加班费',
                        footerFormatter:function (value) {
                            var sumBalance = 0;
                            for (var i in value) {
                                sumBalance += parseFloat(value[i].overtimeFee);
                            }
                            return sumBalance.toFixed(2);
                        }
                    },
                    {
                        field: 'expenseRateFee',
                        title: '报销结算',
                        footerFormatter:function (value) {
                            var sumBalance = 0;
                            for (var i in value) {
                                sumBalance += parseFloat(value[i].expenseRateFee);
                            }
                            return sumBalance.toFixed(2);
                        }
                    },
                    {
                        field: 'otherFee',
                        title: '其他费用'
                    },
                    {
                        field: 'billedFee',
                        title: '已结算费用',
                        footerFormatter:function (value) {
                            var sumBalance = 0;
                            for (var i in value) {
                                sumBalance += parseFloat(value[i].billedFee);
                            }
                            return sumBalance.toFixed(2);
                        }
                    },
                    {
                        field: 'expireTime',
                        title: '收款截止期'
                    },
                    {
                        field: 'totalFee',
                        title: '账单费用',
                        footerFormatter:function (value) {
                            var sumBalance = 0;
                            for (var i in value) {
                                sumBalance += parseFloat(value[i].totalFee);
                            }
                            return sumBalance.toFixed(2);
                        }
                    },
                    {
                        field: 'settleA',
                        title: '结算费用',
                        width: '200px',
                        formatter: function(value, row, index) {
                            var html = $.common.sprintf("<input class='form-control amount' type='text' name='monthBills[%s].amount' value='%s'>", index, row.totalFee- row.billedFee);
                            html = html + $.common.sprintf("<input class='form-control' type='hidden' name='monthBills[%s].projectId' value='%s'>", index, row.projectId);
                            html = html + $.common.sprintf("<input class='form-control' type='hidden' name='monthBills[%s].resourceId' value='%s'>", index, row.id);
                            return html;
                        }
                    }
                ]
		    };
		    $.table.init(options);
		});



	    /* 主子表-提交 */
        function submitHandler(index, layero){
            if ($.validate.form()) {
                var data = $("#form-add").serializeArray();
                //提醒po金额
                var po_total = 0;
                $('.po_amount').each(function (){
                    po_total = po_total + parseFloat($(this).val());
                });
               var total = $('#totalAmount').val();
               if (po_total != total){
                   $.modal.confirm("结算金额和po金额不一致，是否确认提交？",function (){
                       $.operate.saveTab("/erp/settle/add", data);
                   });
               }else
               {
                   $.operate.saveTab("/erp/settle/add", data);
               }

            }

        }

        function addColumn() {
            var customerId = $('#customerId').val();
            if (customerId <= 0){
                $.modal.alertError("请指定需要结算的客户！");
                return;
            }
            var options = {
                title: '选择账单',
                url: "/erp/bill/settle/add/" + customerId,
                width: 1200,
                callBack: onSelectBills
            };
            $.modal.openOptions(options);
        }

        function removeBill(){
            //获取选中的ID
            var ids = $.map($('#bootstrap-table').bootstrapTable('getSelections'), function (row) {
                return row.id;
            });
            //根据Id字段删除对应的数据
            $('#bootstrap-table').bootstrapTable('remove', {field: 'id',values: ids });
            calculateTotal();
        }

        function onSelectBills(index, layero){
            var rows = layero.find("iframe")[0].contentWindow.getSelections();
            rows = removeSelectedItems(rows);
            $("#bootstrap-table").bootstrapTable('append', rows);
            calculateTotal();
            $.modal.close(index);
        }

        function removeSelectedItems(items){
            var datas = $("#bootstrap-table").bootstrapTable('getData');
            var result = [];
            for(let j=0; j < items.length; j++){
                let exist  = false;
                for(let i=0; i< datas.length; i++){
                    if(datas[i].id == items[j].id){
                        exist = true;
                        break;
                    }
                }
                if (!exist) result.push(items[j]);
            }
            return result;

        }

        function footerStyle(column) {
            return {
                totalFee: {
                    css: { color: 'red'}
                }
            }[column.field]
        }

        $(function(){
            $(document).on("blur",'.amount',function(){
                calculateTotal();
            });
        });

        function calculateTotal(){
            var total = 0;
            $('.amount').each(function (){
                total = total + parseFloat($(this).val());
            });
            $('#totalAmount').val(total);
            autoFillPo();
        }

        //处理po

        function onCustomerChange(){
            let customerId = $('#customerId').val();
            $("#bootstrap-table").bootstrapTable("removeAll");
            $('#totalAmount').val(0);
            $.post("/erp/po/list",{"customerId":customerId, "isFinish": "N"},function (data){
                for(let i=0; i< data.rows.length; i++){
                    data.rows[i].settleAmount = 0;
                }
                $("#bootstrap-table-po").bootstrapTable("removeAll");
                $("#bootstrap-table-po").bootstrapTable('append', data.rows);
            });
        }

        //根据结算金额，自动处理
        function autoFillPo(){
            var leftAmount = $('#totalAmount').val();
            let pos = $('#bootstrap-table-po').bootstrapTable("getData");
            for(let i=0; i < pos.length; i++){
                let validAmount = pos[i].orderAmount - pos[i].billedAmount;

                if(validAmount >= leftAmount){
                    pos[i].settleAmount = leftAmount;
                    $('#bootstrap-table-po').bootstrapTable("updateRow",{index: i, row:pos[i]});
                    break;
                }else{
                    pos[i].settleAmount = validAmount;
                    $('#bootstrap-table-po').bootstrapTable("updateRow",{index: i, row:pos[i]});
                    leftAmount = leftAmount - validAmount;
                }
            }
        }

        $(function() {
            $('#customerId').on('change',function (){
               onCustomerChange();
            });

            var options = {
                id: 'bootstrap-table-po',
                modalName: "外派项目PO",
                pagination: false,
                showSearch: false,
                showRefresh: false,
                showToggle: false,
                showColumns: false,
                sidePagination: "client",
                columns: [
                    {
                        field: 'id',
                        title: '',
                        visible: false
                    },
                    {
                        field: 'projectName',
                        title: '项目'
                    },
                    {
                        field: 'title',
                        title: 'po名称'
                    },
                    {
                        field: 'isFinish',
                        title: '已结束',
                        formatter: function(value, row, index) {
                            return $.table.selectDictLabel(isFinishDatas, value);
                        }
                    },
                    {
                        field: 'startDate',
                        title: '开始时间'
                    },
                    {
                        field: 'endDate',
                        title: '结束时间'
                    },
                    {
                        field: 'orderAmount',
                        title: 'PO金额'
                    },
                    {
                        field: 'billedAmount',
                        title: '剩余金额',
                        formatter: function(value, row, index) {
                            let left =  row.orderAmount - value;
                            return left.toFixed(2);
                        }
                    },
                    {
                        title: '消耗金额',
                        field: 'settleAmount',
                        width: '200px',
                        formatter: function(value, row, index) {
                            var html = $.common.sprintf("<input class='form-control po_amount' type='text' name='settlePos[%s].amount' value='%s'>", index, value);
                            html = html + $.common.sprintf("<input class='form-control' type='hidden' name='settlePos[%s].resourceId' value='%s'>", index, row.id);
                            return html;
                        }
                    }]
            };
            $.table.init(options);
        });
    </script>
</body>
</html>